<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
  >
    <template #searchPanel>
      <el-row :gutter="20">
        <search-panel
          @search="search"
          :showAddButton="true"
          @insert="add"
          :addPer="authConfig.add"
          :selectPer="authConfig.query"
          addTitle="新增合同"
        >
          <Job-shop
            clearable
            v-model="formData.storeId"
            placeholder="配车门店"
            @input="sotreChange"
          />
          <el-select
            clearable
            filterable
            style="width: 150px"
            v-model="formData.supplierId"
            placeholder="供应商"
          >
            <!-- <el-option label="全部" value=""></el-option> -->
            <el-option
              v-for="item in supplierOptions"
              :key="item.id"
              :value="item.id"
              :label="item.supplierName"
            />
          </el-select>
          <el-select
            clearable
            style="width: 150px"
            v-model="formData.status"
            placeholder="合同状态"
          >
            <!-- <el-option label="全部" value=""></el-option> -->
            <el-option
              v-for="item in contractStatus"
              :key="item.index"
              :value="item.value"
              :label="item.text"
            />
          </el-select>
          <el-select
            clearable
            style="width: 150px"
            v-model="formData.contractTypeDictId"
            placeholder="合同分类"
          >
            <el-option
              v-for="item in contractDict['合同分类']"
              :key="item.index"
              :value="item.value"
              :label="item.text"
            />
          </el-select>
          <el-date-picker
            v-model="contractTime"
            type="datetimerange"
            range-separator="-"
            start-placeholder="合同开始日期"
            end-placeholder="合同结束日期"
            value-format="yyyy-MM-dd hh:mm:ss"
          >
          </el-date-picker>
        </search-panel>
      </el-row>
    </template>

    <template #contentPanel>
      <data-table
        :value="tableData"
        :total-count="totalCount"
        :has-action="true"
        :table-column-attributes="tableColumnAttributes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @row-dblclick="detailHandle"
        :width="160"
        :isShowPage="true"
      >
        <template #action="{ row }">
          <i
          v-if="row.status === '待审批'"
            class="el-icon-edit"
            title="修改"
            v-permission="authConfig.update"
            style="margin-left: 15px; cursor: pointer"
            @click="editHandle(row)"
          ></i>
          <i
           v-if="row.status === '待审批'"
            class="el-icon-delete"
            title="删除"
            v-permission="authConfig.del"
            style="color: red; margin-left: 15px; cursor: pointer"
            @click="handleDataDelete(row)"
          ></i>
          <i
            v-if="
              isRole && (row.status === '待审批' || row.status === '流转中')
            "
            class="el-icon-collection"
            title="审核"
            style="margin-left: 15px; cursor: pointer"

            @click="approvalHandle(row)"
          ></i>
        </template>
      </data-table>
    </template>
    <template #dialog>
      <ContractDetail
        v-if="dialogTitle === '配车合同详情'"
        :value="dialogData"
      />
      <approval-form
        v-if="dialogTitle === '审核'"
        :approval-data="approvalData"
        @save="approvalSave"
        code="contractNum"
      />
    </template>
  </base-layout>
</template>

<script>
import baseMixin from '@/mixins/base'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import ContractDetail from './ContractDetail'
import ApprovalForm from '@/components/CommonForm/ApprovalForm'

import {
  dataList,
  deleteData,
  getSupplierByStorId,
  details,
  auditIsOk,
} from '@/api/pre-sale/newCarStock/carMatchingContract'
import { mapGetters } from 'vuex'

export default {
  components: { ContractDetail, ApprovalForm },
  mixins: [
    baseMixin({
      idName: 'id',
      findData: dataList,
      dataName: ['content', 'totalRecords'],
      deleteData: deleteData,
      findDataById: details,
      isAdd: false,
      format(res) {
        return res.map((data) => {
          data.rate = data.rate + '%'
          return data;
        });
      }
    }),
  ],
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      authConfig: {
        query: 'contract:page',
        add: 'contract:create',
        edit: 'contract:update',
        del: 'contract:deleted',
        detail: 'contract:detail',
      },
      dialogVisible: false,
      dialogTitle: '配车合同详情',
      dialogWidth: '1000px',
      contractTime: '', // 合同日期
      formData: {
        storeId: '', // 门店id
        supplierId: '', // 供应商id
        status: '', // 合同状态
        maxTime: '', // 合同日期
        minTime: '', // 合同日期
        contractTypeDictId: '', // 合同类型
      },
      contractStatus: getDict(['合同状态'])['合同状态'],
      supplierOptions: [], // 供应商
      // contractTypeOptions: [],
      contractDict: [], // 合同分类
      tableColumnAttributes: [
        { name: '合同编号', value: 'contractNum', type: 'text' },
        { name: '合同状态', value: 'status', type: 'text' },
        { name: '合同分类', value: 'contractTypeDictValue', type: 'text' },
        { name: '配车门店', value: 'storeName', type: 'text' },
        { name: '供应商', value: 'supplierName', type: 'text' },
        { name: '合同金额', value: 'amount', type: 'text' },
        { name: '合同日期', value: 'contractTime', type: 'text' },
        { name: '税率', value: 'rate', type: 'text' },
        { name: '创建人', value: 'createUserName', type: 'text' },
        { name: '备注', value: 'remark', type: 'text' }
      ],
      tableData: [
        {
          id: 1,
          test: 'asdf',
        },
      ],
      detailData: null,
      approvalData: {},
      isRole: false,
    }
  },

  methods: {
    // 门店切换
    sotreChange(newValue) {
      if (!newValue) {
        return
      }
      this.formData.supplierId = ''
      this.formData.contractTypeDictId = ''
      // 查询供应商
      this.getSupplierFun()
      this.contractDict = getDict(['合同分类'], this.formData.storeId)
    },
    // 查看记录
    detailHandle(row) {
      this.dialogTitle = '配车合同详情'
      this.handleDataChange(row, '配车合同详情')
    },
    search() {
      if (this.contractTime && this.contractTime.length > 0) {
        this.formData.minTime = this.contractTime[0]
          ? parseTimeToYMDHMS(this.contractTime[0])
          : ''
        this.formData.maxTime = this.contractTime[1]
          ? parseTimeToYMDHMS(this.contractTime[1])
          : ''
      } else {
        this.formData.minTime = ''
        this.formData.maxTime = ''
      }

      this.searchOptions = this.formData
      this.currentPage = 1
      this.setTableData()
    },
    add() {
      this.$router.push({
        path: '/newCarStock/addCarMatchingContract',
      })
    },
    // 审批
    approvalHandle(row) {
      this.dialogTitle = '审核'
      this.dialogVisible = true
      this.approvalData = row
    },
    // 审核保存
    approvalSave(data) {
      auditIsOk({...data,id:this.approvalData.id}).then((res) => {
        const { success } = res
        if (success) {
           this.approvalData={}
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.setTableData()
        }
        this.dialogVisible = false
      })
    },
    editHandle(row) {
      this.$router.push({
        path: '/newCarStock/editCarMatchingContract',
        query: {
          id: row.id,
        },
      })
    },
    //查询供应商
    async getSupplierFun() {
      let { data } = await getSupplierByStorId(this.formData.storeId, 0)
      this.supplierOptions = data
    },
  },
  created() {
    this.isRole = this.userInfo.roleName.split(',').some((item) => {
      return item === '销售经理' || item === '财务经理' || item === '总经理'
    })
  },
}
</script>

<style lang="scss" scoped>
.vLine {
  border-left: solid 3px black;
  height: 16px;
  vertical-align: bottom;
  display: inline-block;
}
</style>
